<?php
/**
 * common class
 *@date 2012-1-1
 *@autor zhouyongtai
 *@version 1.0
 */
require_once 'Zend/Session/Namespace.php';
class Zyt_Common {

	/**
	 * single instance
	 *@var Zyt_Common
	 */
	protected static $_instance = null;
	protected $user;

	/**
	 * makes "new"
	 *@return void
	 */
	protected function __construct()
	{
		$this->user = new Zend_Session_Namespace("user");
		date_default_timezone_set('PRC');
	}

	/**
	 * makes "clone"
	 *@return void
	 */
	protected function __clone()
	{}

	/**
	 * return an instance of Zyt_Common
	 *@return an instance
	 */
	public static function getInstance()
	{
		if (null === self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
	}

	/**
	 * reponse a string
	 *@return void
	 */
	public function PutData($str)
	{
		header('http-equiv="Content-Type" content="text/html; charset=utf-8"');
		echo $str;	
	}
	
	public function msg($m,  $serr)
	{
		die("<div class=\"wtop b al\" style=\"width:96%;background: #D5DDE5; border: 1px solid #8394B2; color: #000000; margin: .5em 0em .0em .5em; font-size: 12.7px; padding: 5px;\">" . $serr . "</div><div class=\"wmain al\" style=\"width:96%;background: #FAFCFE; border: 1px solid #8394B2; border-top: 0; color: #000000; font-size: 12px; margin: 0em .0em .5em .5em; padding: 5px; line-height:140%;\">" . $m . "</div>");
	}
	/**
	 * check login
	 *@return user
	 */
	public function checklogin($response = true, $isJson = false)
	{
		if(empty($this->user->aln)) {		
			if($response == false) 
			{
				header("Location: /default/default/login");
			}
			else
			{
				if($isJson) 
				{
					$this->PutData('{result:"", error:"用户已被退出，请重新登录！"}');
				}
				else
				{
					$this->msg("需要登录后才能查看本页内容", "出错了");
				}
			}
			exit;
		}
		return array(
			"aln" => $this->user->aln,
			"ali"   => $this->user->ali
		);
	}

	/**
	 * get user id 
	 *@return int id
	 */
	public function getUserid()
	{
		return $this->user->ali;
	}

	
	/**
	 * 获得用户的真实IP地址
	 *
	 * @access  public
	 * @return  string
	 */
	public function getIp()
	{
		static $realip = NULL;

		if ($realip !== NULL)
		{
			return $realip;
		}

		if (isset($_SERVER))
		{
			if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
			{
				$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

				/* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
				foreach ($arr AS $ip)
				{
					$ip = trim($ip);

					if ($ip != 'unknown')
					{
						$realip = $ip;

						break;
					}
				}
			}
			elseif (isset($_SERVER['HTTP_CLIENT_IP']))
			{
				$realip = $_SERVER['HTTP_CLIENT_IP'];
			}
			else
			{
				if (isset($_SERVER['REMOTE_ADDR']))
				{
					$realip = $_SERVER['REMOTE_ADDR'];
				}
				else
				{
					$realip = '0.0.0.0';
				}
			}
		}
		else
		{
			if (getenv('HTTP_X_FORWARDED_FOR'))
			{
				$realip = getenv('HTTP_X_FORWARDED_FOR');
			}
			elseif (getenv('HTTP_CLIENT_IP'))
			{
				$realip = getenv('HTTP_CLIENT_IP');
			}
			else
			{
				$realip = getenv('REMOTE_ADDR');
			}
		}

		preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
		$realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

		return $realip;
	}

	/**
	 * 获得当前格林威治时间的时间戳
	 *
	 * @return  integer
	 */
	public function getGmtime()
	{
		return (time() - date('Z'));
	}

	/**
	 * 获得服务器的时区
	 *
	 * @return  integer
	 */
	function getServertimezone()
	{
		if (function_exists('date_default_timezone_get'))
		{
			return date_default_timezone_get();
			
		}
		else
		{
			return date('Z') / 3600;
		}
	}

	/**
	 * 将GMT时间戳格式化为用户自定义时区日期
	 *
	 * @param  string       $format
	 * @param  integer      $time       该参数必须是一个GMT的时间戳
	 *
	 * @return  string
	 */

	function getLocaldate($time = NULL, $format = NULL)
	{	
		if($format === NULL) 
		{
			$format = "Y-m-d";
		}
		if ($time === NULL)
		{
			$time = $this->getGmtime();
		}
		elseif ($time <= 0)
		{
			return '';
		}

		$time += ($this->getServertimezone() * 3600);

		return date($format, $time);
	}


	/**
	 * 计算字符串的长度（汉字按照两个字符计算）
	 *
	 * @param   string      $str        字符串
	 *
	 * @return  int
	 */
	public function getStrlen($str)
	{
		$length = strlen(preg_replace('/[\x00-\x7F]/', '', $str));

		if ($length)
		{
			return strlen($str) - $length + intval($length / 3) * 2;
		}
		else
		{
			return strlen($str);
		}
	}

	/**
	 * 截取UTF-8编码下字符串的函数
	 *
	 * @param   string      $str        被截取的字符串
	 * @param   int         $length     截取的长度
	 * @param   bool        $append     是否附加省略号
	 *
	 * @return  string
	 */
	public function getSubstr($str, $length = 0, $append = true)
	{
		$str = trim($str);
		$strlength = strlen($str);

		if ($length == 0 || $length >= $strlength)
		{
			return $str;
		}
		elseif ($length < 0)
		{
			$length = $strlength + $length;
			if ($length < 0)
			{
				$length = $strlength;
			}
		}

		if (function_exists('mb_substr'))
		{
			$newstr = mb_substr($str, 0, $length, "UTF-8");
		}
		elseif (function_exists('iconv_substr'))
		{
			$newstr = iconv_substr($str, 0, $length, "UTF-8");
		}
		else
		{
			//$newstr = trim_right(substr($str, 0, $length));
			$newstr = substr($str, 0, $length);
		}

		if ($append && $str != $newstr)
		{
			$newstr .= '...';
		}

		return $newstr;
	}

	public function FxD($s)
	{

		$s = str_replace("\\", "\\", $s);
		$s = str_replace("'", "\'", $s);
		$s = str_replace("\"", "\\\"", $s);
		$s = str_replace("\r","\\r", $s);
		$s = str_replace("\n", "\\n", $s);
		//s = s.Replace("<", "&(lt");
		//s = s.Replace(">", "&(gt");
	
		//s = s.Replace(Environment.)
		
		return $s;
	}
}